package com.interviewbackend.controller;

import com.alibaba.fastjson2.JSON;
import com.interviewbackend.client.ImageAnalysisClient;
import com.interviewbackend.dto.FinalizeRequest;
import com.interviewbackend.dto.MultimodalDataRequestDTO;
import com.interviewbackend.service.MultimodalAnalysisService;
import com.interviewbackend.vo.ResultVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Slf4j
@RestController
@RequestMapping("/api/multimodal-analysis")
public class MultimodalAnalysisController {
    @Resource
    private MultimodalAnalysisService multimodalAnalysisService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 接收前端上传的图像和音频文本数据，进行临时分析并存储结果
     * ✅ 新增：将分析任务的 future 交由服务层追踪
     */
    @PostMapping("/analyze")
    public ResultVO<String> analyzeMultimodalData(@RequestBody MultimodalDataRequestDTO request) {
        CompletableFuture<Void> future = CompletableFuture.runAsync(() ->
                multimodalAnalysisService.analyzeAndStore(request)
        );
        multimodalAnalysisService.trackAnalyzeFuture(request.getSessionId(), future);
        return ResultVO.success("分析任务已提交。");
    }

    /**
     * 异步提交图像URL + 文本，后台处理分析
     */
    @PostMapping("/finalize")
    public ResultVO<Map<String, Object>> finalizeAnalysis(@RequestBody FinalizeRequest request) {
        String sessionId = request.getSessionId();
        String answerText = request.getAnswerText();

        // ✅ 异步执行分析任务
        CompletableFuture.runAsync(() -> {
            multimodalAnalysisService.finalizeAnalysis(sessionId, answerText);
        });
        // ✅ 立即响应“处理中”
        Map<String, Object> data = new HashMap<>();
        data.put("status", "processing");
        data.put("message", "后端正在分析，请稍候...");
        return ResultVO.success(data);
    }
    /**
     * 前端轮询获取分析结果
     */
    @GetMapping("/finalize-result")
    public ResultVO<Map<String, Object>> getFinalResult(@RequestParam String sessionId) {
        String key = "interview:result:" + sessionId;
        String resultJson = stringRedisTemplate.opsForValue().get(key);

        if (resultJson == null) {
            Map<String, Object> data = new HashMap<>();
            data.put("status", "processing");
            return ResultVO.success(data);
        }
        // 一旦获取到，立即删除缓存
        stringRedisTemplate.delete(key);
        Map<String, Object> data = JSON.parseObject(resultJson, Map.class);
        return ResultVO.success(data);
    }
}
